package com.xc.service.impl;

import com.google.common.collect.Lists;
import com.xc.common.ServerResponse;
import com.xc.service.IFileUploadService;
import com.xc.utils.FTPUtil;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Service;
import org.springframework.web.multipart.MultipartFile;

import java.io.File;
import java.util.UUID;

/**
 * @author mipha
 * @version 1.0
 * @date 2019/1/23 2:11 PM
 */
@Service("iFileUploadService")
@Slf4j
public class FileUploadServiceImpl implements IFileUploadService {


    public ServerResponse upload(MultipartFile file , String path){
        //  原文件名
        String fileName = file.getOriginalFilename();

        //  扩展名
        String fileExtentionName = fileName.substring(fileName.lastIndexOf(".") + 1);

        String uploadFileName = UUID.randomUUID() + "." + fileExtentionName;

        File fileDir = new File(path);

        if(!fileDir.exists()){
            //  不存在就创建文件夹
            fileDir.setWritable(true);
            fileDir.mkdirs();
        }

        File tartgetFile = new File(path , uploadFileName);
        boolean result = false;
        try {
            file.transferTo(tartgetFile);

            // TODO: 2019/1/23  将targetFile上传到FTP服务器
            result = FTPUtil.uploadFile(Lists.newArrayList(tartgetFile));
            // TODO: 2019/1/23 删除upload下面的文件
            tartgetFile.delete();

        }catch (Exception e){
            log.error("上传文件异常 , 错误信息 = {}", e);
            return null;
        }

        if(result){
            return ServerResponse.createBySuccess(tartgetFile.getName());
        }else{
            return ServerResponse.createByErrorMsg("上传失败");
        }
    }







}


